var id;

  jQuery.ajax({
    url: '/problem' + location.search,
    method: 'get',
    headers: {
      'Authorization': localStorage.getItem("token")
    },
    success: function(result){
      if(result != null){
        if(result.code==200){
            // 获取题目父标签
            var desc = document.querySelector('.description flex fdc');
            // 获取题目名字
            var title = document.querySelector('.title');
            title.innerHTML = result.data.id + ". " + result.data.title + " (" + result.data.level +")";
            // 获取正文
            var content = document.querySelector('.desc');
            content.innerText = result.data.description;
            // 获取代码模板
            editor.setValue(result.data.templateCode)

            id = result.data.id;
            
        }else{
            alert("题目获取失败，需要先登录！" + result.msg);
            location.href = "login.html";
        }
      }else{
            alert("后端服务不可用！");
      }
    }
  });

  function initAce(){
    let editor = ace.edit("editor");
    editor.setOptions({
        // 支持自动补全
        enableBasicAutocompletion: true,
        // 支持代码模板
        enableSnippets: true,
        // 模板自动补全
        enableLiveAutocompletion: true
    });
    // 设置主题
    editor.setTheme("ace/theme/katzenmilch");
    // 设置语言
    editor.session.setMode("ace/mode/java");

    editor.resize();
    // 字体
    document.getElementById('editor').style.fontSize = '20px';

    return editor;
  }

  let editor = initAce();


  function submit(){
    popUp();
    console.log(id);
      let body = {
          id: id,
          code: editor.getValue(),
          token: localStorage.getItem("token")
      }
     jQuery.ajax({
        url: 'compile',
        method: 'post',
        data: JSON.stringify(body),
        contentType:'application/json',
        headers: {
            'Authorization': localStorage.getItem("token")
        },
        success: function(result){
          if(result != null){
            if(result.code == 200){
              buildCodingResult(result.data);
            }else{
              // 对应后端内容未修改完
              alert('我是一个bug！');
            }
          }else{
            alert('后端服务不可用！');
          }
        }
    });
}
function popUp(){
  var popUp = document.querySelector('.pop-up');
  popUp.style.display = 'block';
}
function buildCodingResult(data){
  var consequence= document.querySelector('#consequence');
  var text = document.querySelector('#result');
  var icon = document.querySelector('.judge-icon')
  if(data.error == 0){
    icon.innerHTML = '&#xe600;';
    icon.style.color = '#458f41'
    consequence.innerHTML = '评测已通过';
    text.innerHTML = null;
  }else{
    icon.innerHTML = '&#xe601;';
    icon.style.color = '#d61b03';
    consequence.innerHTML = '评测未通过';
    text.innerHTML = data.reason;
  }
}
function Close(){
  var popUp = document.querySelector('.pop-up');
  popUp.style.display = 'none';
}